package com.example.test06thread.collectionThread;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: fxy
 * @Date: 2022/05/27/8:29
 * @Description:
 * HashSet<>()不安全，多个线程存在ConcurrentModificationException：并发修改异常
 *          * 解决方案：1、工具类把它变安全：Collections.synchronizedSet(new HashSet<>());
 *          * 2、CopyOnWriteArraySet
 */
public class SetTest {
    public static void main(String[] args) {
        SetTest setTest = new SetTest();
        //setTest.setTest();
        //setTest.synchronizedSetTest();
        setTest.copyOnWriteArraySetTest();

    }

    public void setTest(){
        Set<String> set = new HashSet<>();
        for (int i=0;i<=100;i++){
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

    public void synchronizedSetTest(){
        Set<String> set = Collections.synchronizedSet(new HashSet<>());
        for (int i=0;i<=100;i++){
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

    public void copyOnWriteArraySetTest(){
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i=0;i<=100;i++){
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

}
